package com.hexb.core.utils;

import com.hexb.core.common.DruidDataSourceHelper;
import com.hexb.core.common.IDataSourceProperties;
import com.hexb.core.enums.AscColors;
import com.hexb.core.properties.DataSourceProperties;
import com.hexb.core.properties.DruidProperties;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;

/**
 * @Package : com.hexb.core.utils
 * @Author : hexb
 * @Date : 2018-08-7 14:38
 */
@Slf4j
public class DruidDataSourceBuilder {

    final static String DRUID_CLASS = "com.alibaba.druid.pool.DruidDataSource";

    private DataSource dataSource;

    public DruidDataSourceBuilder() {
        String error = String.format("%s====>%s %sCreate DruidDataSource Error%s",
                AscColors.YELLOW, AscColors.END,
                AscColors.RED, AscColors.END);
        try {
            dataSource = (DataSource) Class.forName(DRUID_CLASS).newInstance();
        } catch (InstantiationException e) {
            log.error(error, e);
        } catch (IllegalAccessException e) {
            log.error(error, e);
        } catch (ClassNotFoundException e) {
            log.error(error, e);
        }
    }

    public DruidDataSourceBuilder druid(DruidProperties druidProperties) {
        DruidDataSourceHelper.bindProperties(dataSource, druidProperties);
        return this;
    }

    public DruidDataSourceBuilder jdbc(IDataSourceProperties jdbcProperties) {
        DruidDataSourceHelper.bindJdbc(dataSource, jdbcProperties);
        return this;
    }

    public DataSource build() {
        return this.dataSource;
    }
}
